package com.googlecode.lookie.imagedb.internal;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Timestamp;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.jdbc.core.simple.ParameterizedRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;

import com.googlecode.lookie.imagedb.ImageDao;
import com.googlecode.lookie.imagedb.ImageData;

public class JdbcImageDao
    implements ImageDao
{

    private SimpleJdbcTemplate template;

    public JdbcImageDao( DataSource dataSource )
    {
        super();
        template = new SimpleJdbcTemplate( dataSource );
    }

    public synchronized void delete( String id )
    {
        template.update( "DELETE FROM image WHERE id = ?", id );
        template.update( "DELETE FROM image_data WHERE id = ?", id );
    }

    public synchronized ImageData getImageData( String id )
    {
        ParameterizedRowMapper<ImageData> rowMapper = new ParameterizedRowMapper<ImageData>()
        {
            public ImageData mapRow( ResultSet rs, int rowNum )
                throws SQLException
            {

                ImageData d = new ImageData();
                d.setId( rs.getString( "id" ) );
                d.setLastModified( rs.getTimestamp( "last_modified" ).getTime() );

                return d;
            }
        };

        List<ImageData> imageDataList = template.query( "SELECT id, last_modified FROM image_data WHERE id = :id",
                                                        rowMapper, id );

        return imageDataList.size() == 0 ? null : imageDataList.get( 0 );
    }

    public synchronized byte[] getImage( String id )
    {
        ParameterizedRowMapper<byte[]> rowMapper = new ParameterizedRowMapper<byte[]>()
        {
            public byte[] mapRow( ResultSet rs, int rowNum )
                throws SQLException
            {

                return rs.getBytes( "data" );
            }
        };

        byte[] image = (byte[]) template.queryForObject( "SELECT data FROM image WHERE id = :id", rowMapper, id );

        return image;
    }

    public synchronized void insert( ImageData data, byte[] bs )
    {
        template.update( "INSERT INTO image VALUES(?, ?)", data.getId(), bs );
        template.update( "INSERT INTO image_data VALUES(?, ?)", data.getId(), new Timestamp( data.getLastModified() ) );
    }

    public synchronized void update( ImageData data, byte[] bs )
    {
        template.update( "UPDATE image SET data = ? WHERE id = ?", bs, data.getId() );
        template.update( "UPDATE image_data SET last_modified = ? WHERE id = ?",
                         new Timestamp( data.getLastModified() ), data.getId() );
    }

}
